package com.wu.server.controller;

import com.wu.server.code.Code;
import com.wu.server.entity.Shop;
import com.wu.server.service.ShopServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class ShopController {
    @Autowired
    Code code;
    @Autowired
    ShopServer shopServer;
    @GetMapping("shop")
    @ResponseBody
    public Object getShop(
            @RequestParam(value = "id", defaultValue = "") String shopId,
            @RequestParam(value = "shopName", defaultValue = "") String shopName,
            @RequestParam(value = "salesRange", defaultValue = "0,999999999") String salesRange,
            @RequestParam(value = "sort", defaultValue = "id") String sort,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "order", defaultValue = "desc") String order
    ){
        return shopServer.queryShop(shopId,shopName,salesRange,order,sort,pageNum,pageSize);
    }
    @PostMapping("shop")
    @ResponseBody
    public Object addShop(@RequestBody ShopForm form){
        Shop shop = new Shop();
        shop.shop_name = form.shopName;
        shop.shop_sales = form.sales;
        if(form.shopName == null || form.shopName.equals("")) return code.getMeta(Code.PARAM_ERROR,null);
        return shopServer.insertShop(shop);
    }
    @PutMapping("shop")
    @ResponseBody
    public Object updateShop(@RequestBody ShopForm form){
        Shop shop = new Shop();
        shop.id = form.id;
        shop.shop_name = form.shopName;
        shop.shop_sales = form.sales;
        if(form.shopName == null || form.id == 0) return code.getMeta(Code.PARAM_ERROR,null);
        return shopServer.updateShop(shop);
    }
    @DeleteMapping("shop")
    public Object deleteShop(@RequestParam(value = "id") int id){
        if(id == 0) return code.getMeta(Code.PARAM_ERROR,null);
        return shopServer.deleteShop(id);
    }
    private static class ShopForm{
        public int id;
        public String shopName;
        public int sales;
    }
}
